package com.example.demo101.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

/**
 * AuthConfig
 *
 * @author lichao
 * @version 1.0.0
 * @since 2025/6/28 19:49
 */
@Configuration
public class AuthConfig {

    public static final String AUTH_HEADER = "Authorization";

    @Bean
    public SecurityFilterChain  securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.formLogin(f->{
            f.loginPage("/login")
                    .successHandler(new AuthenticationSuccessHandler() {
                        @Override
                        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

                        }

                        @Override
                        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
                            AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
                        }
                    })
                    .failureHandler(new AuthenticationFailureHandler() {
                        @Override
                        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

                        }
                    });

        })
                .oauth2Login(null)
                .authorizeHttpRequests(null)
                .oauth2ResourceServer(null)
                .oauth2Client(null)
                .csrf(null)
                .exceptionHandling(null)
                .sessionManagement(null);


        DefaultSecurityFilterChain build = httpSecurity.build();
        return build;
    }
}
